import 'reflect-metadata'
import helmet from 'koa-helmet'
import Koa from 'koa'
import Router = require('koa-router');
import { Container } from 'typedi'
import { ConnectionManager, createConnection, getConnectionManager } from 'typeorm'
import { useContainer as routingUseContainer, useKoaServer } from 'routing-controllers'
import { PORT, IS_DEV } from './config'
import {
  databaseConfig,
} from './config/database'
import { getSpec } from './utils/swagger';
import { SessionMiddleware } from './middleware/session';
import { AuthCheckMiddleware } from './middleware/authCheck';
import { BASE_URL } from './constants/request';

routingUseContainer(Container)
createConnection(databaseConfig).then(async (connection: any) => {
  console.log('Database connected');
  const connectionManager = getConnectionManager();
  Container.set(ConnectionManager, connectionManager);
});

const app = useKoaServer(new Koa(), {
  cors: true,
  routePrefix: BASE_URL,
  development: IS_DEV,
  controllers: [__dirname + '/controller/*.ts'],
  middlewares: [SessionMiddleware, AuthCheckMiddleware],
})

app.use(helmet())

const router = new Router();
router.get('/swagger.json', async (ctx) => {
  ctx.body = getSpec();
  ctx.status = 200;
});

app.use(router.routes()); // Use the router middleware

app.listen(PORT)

console.log(`Server running on port ${PORT}`);
